package com.chuangke.file.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chuangke.admin.data.builder.UserDataBuilder;
import com.chuangke.common.data.builder.DataBuildConfig;
import com.chuangke.common.data.builder.DataBuilder;
import com.chuangke.common.idgen.IdManager;
import com.chuangke.common.utils.SecurityUtils;
import com.chuangke.file.dao.FileDownloadHistoryMapper;
import com.chuangke.file.model.FileDownloadHistory;
import com.chuangke.file.service.FileDownloadHistoryService;

@Service
public class FileDownloadHistoryServiceImpl extends ServiceImpl<FileDownloadHistoryMapper, FileDownloadHistory> implements FileDownloadHistoryService {
	
	@Autowired
	private FileDownloadHistoryMapper fileDownloadHistoryMapper;

	@Override
	public List<FileDownloadHistory> findFileDownloadRecord(String id) {
		List<FileDownloadHistory> fileList = fileDownloadHistoryMapper
				.selectList(new QueryWrapper<FileDownloadHistory>().lambda().eq(FileDownloadHistory::getFileId, id));
		DataBuilder.of(fileList).appendBuilder(new UserDataBuilder(), new DataBuildConfig("downloadBy", "downloadBy"))
				.build();
		return fileList;
	}

	@Override
	public int save(String fileId) {
		return fileDownloadHistoryMapper.insert(getBean(fileId));
	}
	
	private FileDownloadHistory getBean(String fileId) {
		FileDownloadHistory downHistory = new FileDownloadHistory();
		downHistory.setId(IdManager.nextId());
		downHistory.setFileId(fileId);
		downHistory.setDownloadBy(SecurityUtils.getUserId());
		downHistory.setDownloadAt(new Date());
		return downHistory ;
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void saveBatch(List<String> fileIds) {
		if(fileIds==null || fileIds.isEmpty()) {
			return ;
		}
		
		List<FileDownloadHistory> list = new ArrayList<>(fileIds.size()) ;
		fileIds.forEach(fileId-> list.add(getBean(fileId)));
		this.saveBatch(list) ;
	}
}
